// internal/dao/database.go
package dao

import (
	"fmt"
	"log"
	"time"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"

	"github.com/jfastfiler/internal/model"
)

type Database struct {
	db *gorm.DB
}

func NewDatabase(dsn string, maxConn, idleConn int, connLifetime time.Duration) (*Database, error) {
	db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
		NowFunc: func() time.Time {
			return time.Now().UTC()
		},
	})
	if err != nil {
		return nil, fmt.Errorf("failed to connect database: %v", err)
	}

	sqlDB, err := db.DB()
	if err != nil {
		return nil, err
	}

	// 设置连接池
	sqlDB.SetMaxOpenConns(maxConn)
	sqlDB.SetMaxIdleConns(idleConn)
	sqlDB.SetConnMaxLifetime(connLifetime)

	// 自动迁移表结构
	err = db.AutoMigrate(
		&model.User{},
		&model.FileMetadata{},
		&model.Permission{},
		&model.AuditLog{},
		&model.ShareLink{},
		&model.Tag{},
		&model.FileTag{},
		&model.SearchHistory{},
		&model.SystemConfig{},
	)
	if err != nil {
		return nil, fmt.Errorf("failed to migrate database: %v", err)
	}

	log.Println("Database initialized successfully")
	return &Database{db: db}, nil
}

func (d *Database) GetDB() *gorm.DB {
	return d.db
}

func (d *Database) Close() error {
	sqlDB, err := d.db.DB()
	if err != nil {
		return err
	}
	return sqlDB.Close()
}

// 初始化数据库数据
func (d *Database) InitData() error {
	// 检查是否已初始化
	var count int64
	d.db.Model(&model.User{}).Count(&count)
	if count > 0 {
		return nil
	}

	// 创建默认管理员用户
	adminUser := &model.User{
		Username:     "admin",
		PasswordHash: "$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi", // password: admin123
		Email:        "admin@jfastfiler.com",
		Role:         "admin",
		RealName:     "系统管理员",
		Status:       1,
		CreatedAt:    time.Now(),
	}

	if err := d.db.Create(adminUser).Error; err != nil {
		return err
	}

	// 创建根目录
	rootDir := &model.FileMetadata{
		UUID:       generateUUID(),
		Path:       "/",
		Name:       "根目录",
		IsDir:      true,
		OwnerID:    adminUser.ID,
		CreateTime: time.Now(),
		ModTime:    time.Now(),
	}

	if err := d.db.Create(rootDir).Error; err != nil {
		return err
	}

	// 创建默认权限
	permissions := []model.Permission{
		{
			Path:        "/",
			Role:        "admin",
			CanView:     true,
			CanDownload: true,
			CanEdit:     true,
			CanDelete:   true,
			CanShare:    true,
			CanPreview:  true,
			Priority:    100,
			CreatedBy:   adminUser.ID,
		},
		{
			Path:        "/",
			Role:        "user",
			CanView:     true,
			CanDownload: true,
			CanEdit:     true,
			CanDelete:   false,
			CanShare:    true,
			CanPreview:  true,
			Priority:    50,
			CreatedBy:   adminUser.ID,
		},
	}

	for _, perm := range permissions {
		if err := d.db.Create(&perm).Error; err != nil {
			return err
		}
	}

	// 创建默认系统配置
	configs := []model.SystemConfig{
		{ID: "site_name", Value: "JFastFiler", Desc: "站点名称"},
		{ID: "site_description", Value: "高性能文件管理系统", Desc: "站点描述"},
		{ID: "allow_registration", Value: "false", Desc: "允许用户注册"},
		{ID: "max_file_size", Value: "10737418240", Desc: "最大文件大小"},
		{ID: "allowed_extensions", Value: "jpg,jpeg,png,gif,pdf,doc,docx,xls,xlsx,ppt,pptx,txt,zip,rar", Desc: "允许的文件扩展名"},
	}

	for _, cfg := range configs {
		if err := d.db.Create(&cfg).Error; err != nil {
			return err
		}
	}

	log.Println("Default data initialized successfully")
	return nil
}

func generateUUID() string {
	return fmt.Sprintf("%x", time.Now().UnixNano())
}